<?php
/**
 * 
 * @author tangbl
 * 
 */
class WxlogModel extends Model {
	
	//用户关注
	public function subscribe($data){
		$member = M("Memberwx");
		$where  = "FromUserName = '".$data['FromUserName']."'";
		$rows   = $member->where($where)->find();
		
		$rec['ToUserName']   = $data['ToUserName'];
		$rec['FromUserName'] = $data['FromUserName'];
		$rec['openid']       = myencrypt($data['FromUserName']);
		$rec['addtime']      = $data['CreateTime'];
		
		if($rows['id']){
			$rec['issub'] = 1 ;
			$rec['id']    = $rows['id'] ;
			$member ->save($rec);
		}else{
			$member ->add($rec);
		}
	}
	
	//用户取消关注
	public function unsubscribe($data){
		$member = M("Memberwx");
		$where  = "FromUserName = '".$data['FromUserName']."'";
		$rows   = $member->where($where)->find();
		
		$rec['issub'] = 2;
		$rec['id']    = $rows['id'] ;
		$member ->where()->save($rec);
	}
	
	public function replyTalk($key){
		
		$pattern = "/^http:\\/\\/mp.weixin.qq.com/";
		if(preg_match($pattern,$key)){
			return $this->storgeUrlToContent($key);
		}else{
			return false;
		}
	}

	//转储微信链接为本地文章
	private function storgeUrlToContent($url){
		import('ORG.Wechat.Snoopy');
		$snoopy = new Snoopy;
		$snoopy->fetch($url);

		$html    = $snoopy->results;   //显示结果
		$title   = $snoopy->getTitle();//获取标题
		$single  = $snoopy->getCent('<img src=\"', '" onerror=');//获取缩略图URL
		$writer  = $snoopy->getCent('<span class=\"text-ellipsis\">', '<\/span><i class=\"icon_link_arrow\">');
		$content = $snoopy->getCent('<div class=\"text\">','<p class=\"page-toolbar\">');
		$content = $snoopy->saveImg($content);//存储内容中的远程图片到本地
		
		$solevar = create_id();
		$addtime = time();
		$lang    = "zh-cn";
		$source  = "微信";
		$cateid  = 56;

		$upload = "Caiji/".date("Ymd")."/";
		$abpath = ABS_PATH.UPLOAD_URL.$upload;
		$image  = $snoopy->downloadImage($single,$abpath);
		
		$model = M("Article");
		$model->solevar     = $solevar;
		$model->lang        = $lang;
		$model->cateid      = $cateid;
		$model->title       = $title;
		$model->writer      = $writer;
		$model->source      = $source;
		$model->description = $title;
		$model->content     = $content;
		$model->addtime     = $addtime;
		
		$id = $model->add();
		
		//保存缩略图
		if($id){
			if($image){
				$model = M("Relefile");
				$data["c_table"]   = "Article";
				$data["c_solevar"] = $solevar;
				$data["c_title"]   = $title;
				$data["fileurl"]   = $upload.$image['name'];
				$data["c_affect"]  = "single";
				$data["addtime"]   = time();
				$model->add($data);
			}
			$url   = "<a href='".ABS_URL."wechat.php?s=Article/detail/id/".$id."'>测试文章</a>"; 
			$text  = "转换链接成文章成功,".$url;
			$reply = array(array("Description"=>$text),"text");
		}else{
			$reply = array(array("Description"=>"转换链接成文章失败"),"text");
		}
		
		return $reply;
	}
	
}
?>